let express = require('express');
let crypto = require('crypto');
let router = express.Router();
let filter = require('../../components/filter');

/**
 * 查询机构数据 by p 2018-06-11
 *
 * 按条件查询机构数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;

    var limits = "";
    var sql = "";
    var datas = [];

    if (params.fatherId !== undefined && params.fatherId !== "") {
        sql = " where fatherId = ? ";
        datas.push(params.fatherId);
    }

    if (params.manageId !== undefined && params.manageId !== "") {
        sql = (sql === "" ? " where " : " and ") + " manageId = ? ";
        datas.push(params.manageId);
    }

    req.app.db.query("select count(1) as totalCount from department " + sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from department " + sql + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }
            res.json({"success": true, "data": results, "totalCount": totalCount, "message": ""});
        });
    });
});

/**
 * 查看机构数据 by p 2018-06-11
 *
 * 按id查看指定的机构信息
 */
router.get('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query("select * from department where id = ?", [params.id], function (err, results, fields) {
        console.log(fields);
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});

/**
 * 修改机构数据 by p 2018-06-11
 *
 *
 */
router.put('/:id', filter.authorize, function (req, res, next) {
    let params = req.body;
    let isWork = 0;
    let isStatistics = 0;

    if (params.id === undefined || params.id === '') {
        res.json({"success": false, "message": "机构编码错误！"});
        return;
    }

    if (params.name === undefined || params.name === "") {
        res.json({"success": false, "message": "机构名称不能为空！"});
        return;
    }

    if (params.fatherId === undefined || params.fatherId === "") {
        res.json({"success": false, "message": "必须指定父机构！"});
        return;
    }

    if (params.isWork !== undefined || params.isWork !== "") {
        isWork = params.isWork;
    }

    if (params.isStatistics !== undefined || params.isStatistics !== "") {
        isStatistics = params.isStatistics;
    }

    if (params.manageId === undefined || params.manageId === "") {
        res.json({"success": false, "message": "必须指定机构的管理部门！"});
        return;
    }

    req.app.db.query("select * from department where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        let deparment = results[0];

        // 更换管理部门，前提是当前单位不能有指标信息，否则会影响整个数据平衡
        if (deparment.manageId !== params.manageId) {
            req.app.db.query("select 1 from quota where departmentId = ?", [params.id], function (err, results, fields) {
                if (err) {
                    res.json({"success": false, "message": global.databaseErr, "detail": err});
                    return;
                }

                if (results.length > 0) {
                    res.json({"success": false, "message": "当前单位存在年度指标信息，不能修改管理单位！"});
                    return;
                }

                req.app.db.query("update department set name = ?, fatherId = ?, isWork = ?, isStatistics = ?, length = ?, manageId = ? where id = ?", [params.name, params.fatherId, isWork, isStatistics, params.id.length, params.manageId, params.id], function (err, results) {
                    if (err) {
                        res.json({"success": false, "message": global.databaseErr, "detail": err});
                        return;
                    }

                    res.json({"success": true, "message": global.putMsg});
                });
            });
        }
        else {
            req.app.db.query("update department set name = ?, fatherId = ?, isWork = ?, isStatistics = ?, length = ?, manageId = ? where id = ?", [params.name, params.fatherId, isWork, isStatistics, params.id.length, params.manageId, params.id], function (err, results) {
                if (err) {
                    res.json({"success": false, "message": global.databaseErr, "detail": err});
                    return;
                }

                res.json({"success": true, "message": global.putMsg});
            });
        }
    });
});

/**
 * 新增机构数据 by p 2018-06-11
 *
 *
 */
router.post('/', filter.authorize, function (req, res, next) {
    let params = req.body;
    let isWork = 0;
    let isStatistics = 0;

    if (params.id === undefined || params.id === '') {
        res.json({"success": false, "message": "机构编码错误！"});
        return;
    }

    if (params.name === undefined || params.name === "") {
        res.json({"success": false, "message": "机构名称不能为空！"});
        return;
    }

    if (params.fatherId === undefined || params.fatherId === "") {
        res.json({"success": false, "message": "必须指定父机构！"});
        return;
    }

    if (params.isWork !== undefined || params.isWork !== "") {
        isWork = params.isWork;
    }

    if (params.isStatistics !== undefined || params.isStatistics !== "") {
        isStatistics = params.isStatistics;
    }

    if (params.manageId === undefined || params.manageId === "") {
        res.json({"success": false, "message": "必须指定机构的管理部门！"});
        return;
    }

    req.app.db.query("insert into department(id, name, fatherId, isWork, isStatistics, length, manageId) values(?, ?, ?, ?, ?, ?, ?)", [params.id, params.name, params.fatherId, isWork, isStatistics, params.id.length, params.manageId], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.postMsg});
    });
});

/**
 * 删除机构信息 by v 2018-06-11
 *
 * 按id删除指定的机构信息
 */
router.delete('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query("select 1 from quota where departmentId = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length > 0) {
            res.json({"success": false, "message": "当前单位存在年度指标信息，不能删除！"});
            return;
        }

        req.app.db.query('delete from department where id = ?', [params.id], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "message": global.deleteMsg});
        });
    });
});

module.exports = router;